import json
import copy
import time
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *
import logging
import requests

get_version_list_api = Blueprint('get_version_list_api', __name__)
compare_version_api = Blueprint('compare_version_api', __name__)
compare_pid_api = Blueprint('compare_pid_api', __name__)
get_effective_version_info_api = Blueprint('get_effective_version_info_api', __name__)

@get_version_list_api.route('/get_version_list', methods=['POST'])
def get_version_list():
    resp = {
        'status': 'success',
        'message': ''
    }
    try:
        params = json.loads(request.data)
        event = str(params['event'])

    except Exception as e:
        logging.exception(e)
        resp['status'] = 'error'
        resp['message'] = "请求参数错误"
        return jsonify(resp)

    query = ProjectVersionSnapshot.query.filter_by(event=event).order_by(ProjectVersionSnapshot.created_at.desc()).all()
    version_list = []
    for i in query:
        version_list.append({
            'id': i.id,
            'hash': i.hash,
            'created_time': fomat_timestamp(i.created_at)
        })
    resp['version_list'] = version_list

    return jsonify(resp)


@compare_version_api.route('/compare_version', methods=['POST'])
def compare_version():
    resp = {
        'status': 'success',
        'message': ''
    }

    try:
        params = json.loads(request.data)
        event = str(params['event'])
        version_1 = int(params['version_1'])
        version_2 = int(params['version_2'])

    except Exception as e:
        logging.exception(e)
        resp['status'] = 'error'
        resp['message'] = "请求参数错误"
        return jsonify(resp)

    version_1_query = ProjectVersionSnapshot.query.filter_by(event=event, id=version_1).first()
    version_2_query = ProjectVersionSnapshot.query.filter_by(event=event, id=version_2).first()
    if version_1_query is None:
        resp['status'] = 'fail'
        resp['message'] = f"[version_1={version_1}] 获取待比对版本记录失败"
        return jsonify(resp)
    if version_2_query is None:
        resp['status'] = 'fail'
        resp['message'] = f"[version_2={version_2}] 获取待比对版本记录失败"
        return jsonify(resp)

    try:
        version_1_data = json.loads(version_1_query.data)
        version_2_data = json.loads(version_2_query.data)
        version_1_list = []
        version_2_list = []
        for i in version_1_data:
            current_project = int(i)
            current_project_data = version_1_data[i]
            status = ''
            if i not in version_2_data:
                status = 'new'
            else:
                compare_data = version_2_data[i]
                if current_project_data == compare_data:
                    status = 'noChange'
                else:
                    status = 'change'
            version_1_list.append({
                'project': current_project,
                'remark': current_project_data['remark'],
                'status': status
            })
        for i in version_2_data:
            current_project = int(i)
            current_project_data = version_2_data[i]
            status = ''
            if i not in version_1_data:
                status = 'new'
            else:
                compare_data = version_1_data[i]
                if current_project_data == compare_data:
                    status = 'noChange'
                else:
                    status = 'change'
            version_2_list.append({
                'project': current_project,
                'remark': current_project_data['remark'],
                'status': status
            })

        resp['pid_list'] = {
            'version_1': version_1_list,
            'version_2': version_2_list
        }

    except Exception as e:
        logging.exception(e)
        resp['status'] = 'error'
        resp['message'] = "比对过程发生未知错误"
        return jsonify(resp)

    return jsonify(resp)


@compare_pid_api.route('/compare_pid', methods=['POST'])
def compare_pid():
    resp = {
        'status': 'success',
        'message': ''
    }

    try:
        params = json.loads(request.data)
        event = str(params['event'])
        pid_1 = int(params['pid_1'])
        pid_1_version = int(params['pid_1_version'])
        pid_2 = int(params['pid_2'])
        pid_2_version = int(params['pid_2_version'])

    except Exception as e:
        logging.exception(e)
        resp['status'] = 'error'
        resp['message'] = "请求参数错误"
        return jsonify(resp)

    version_1_query = ProjectVersionSnapshot.query.filter_by(event=event, id=pid_1_version).first()
    version_2_query = ProjectVersionSnapshot.query.filter_by(event=event, id=pid_2_version).first()
    if version_1_query is None:
        resp['status'] = 'fail'
        resp['message'] = f"[pid_1_version={pid_1_version}] 获取待比对版本记录失败"
        return jsonify(resp)
    if version_2_query is None:
        resp['status'] = 'fail'
        resp['message'] = f"[pid_2_version={pid_2_version}] 获取待比对版本记录失败"
        return jsonify(resp)

    try:
        version_1_data = json.loads(version_1_query.data)
        version_2_data = json.loads(version_2_query.data)
        if str(pid_1) not in version_1_data:
            resp['status'] = 'fail'
            resp['message'] = f"[pid_1_version={pid_1_version}, pid_1={pid_1}] 获取配置失败"
            return jsonify(resp)
        if str(pid_2) not in version_2_data:
            resp['status'] = 'fail'
            resp['message'] = f"[pid_2_version={pid_2_version}, pid_2={pid_2}] 获取配置失败"
            return jsonify(resp)
        pid_1_data = version_1_data[str(pid_1)]
        pid_2_data = version_2_data[str(pid_2)]

        event_config = get_file_compare_config(event)
        if 'tab_list' not in event_config:
            resp['status'] = 'fail'
            resp['message'] = f"[event={event}] 获取 tab 列表失败"
            return jsonify(resp)
        tab_list = []
        for i in event_config['tab_list']:
            current_dependence = i['dependence']
            change = False
            for j in current_dependence:
                if j not in pid_1_data or j not in pid_2_data:
                    change = True
                    break
                if pid_1_data[j] != pid_2_data[j]:
                    change = True
                    break
            tab_list.append({
                'name': i['name'],
                'change': change
            })

        resp['tab_list'] = tab_list
    except Exception as e:
        logging.exception(e)
        resp['status'] = 'error'
        resp['message'] = "比对过程发生未知错误"
        return jsonify(resp)

    return jsonify(resp)


@get_effective_version_info_api.route('/get_effective_version_info', methods=['POST'])
def get_effective_version_info():
    resp = {
        'status': 'success',
        'message': ''
    }

    try:
        params = json.loads(request.data)
        event = str(params['event'])

    except Exception as e:
        logging.exception(e)
        resp['status'] = 'error'
        resp['message'] = "请求参数错误"
        return jsonify(resp)

    try:
        md5_object = get_file_compare_md5_default_object(event)
        current_temp_object = copy.deepcopy(md5_object)
        current_object = copy.deepcopy(md5_object)
        online_temp_object = copy.deepcopy(md5_object)
        online_object = copy.deepcopy(md5_object)
        for file_name in md5_object:
            current_temp_object[file_name] = \
            s3_client.s3_file_info('leyi-qa-autotest', f'westgame_{EVN}/tmp/{file_name}.json')['md5']
            current_object[file_name] = s3_client.s3_file_info('leyi-qa-autotest', f'westgame_{EVN}/{file_name}.json')[
                'md5']
            online_temp_object[file_name] = \
            s3_client.s3_file_info_online('leyi-game-static-file', f'westgame_online/tmp/{file_name}.json')['md5']
            online_object[file_name] = \
            s3_client.s3_file_info_online('leyi-game-static-file', f'westgame_online/check_s3/{file_name}.json')['md5']

        current_temp_hash = hashlib.md5(json.dumps(current_temp_object, sort_keys=True).encode('utf-8')).hexdigest()
        current_hash = hashlib.md5(json.dumps(current_object, sort_keys=True).encode('utf-8')).hexdigest()
        online_temp_hash = hashlib.md5(json.dumps(online_temp_object, sort_keys=True).encode('utf-8')).hexdigest()
        online_hash = hashlib.md5(json.dumps(online_object, sort_keys=True).encode('utf-8')).hexdigest()

        resp['result'] = {
            'current': {
                'hash': current_hash
            },
            'current_temp': {
                'hash': current_temp_hash
            },
            'online': {
                'hash': online_hash
            },
            'online_temp': {
                'hash': online_temp_hash
            }
        }
    except Exception as e:
        logging.exception(e)
        resp['status'] = 'error'
        resp['message'] = "发生未知错误"
        return jsonify(resp)

    return jsonify(resp)
